from tkinter import *
import get_lines as gl
import tkinter.messagebox as messagebox
import datetime
import threading
import asyncio
import time
import os


def check(parent,buy_tips, sell_tips, stock):
    today = datetime.datetime.today()
    os.path.exists('stocks/2020/')
    last_week = today + datetime.timedelta(-30)
    data = gl.query_history_k_data_plus(stock,
                                        last_week.strftime('%Y-%m-%d'),
                                        today.strftime('%Y-%m-%d'))
    stock_info = Toplevel(parent)
    stock_info.geometry('500x400')
    stock_info.title('%s行情' % stock)
    frame_packs = PanedWindow(stock_info, showhandle=False, sashrelief=SUNKEN, orient=VERTICAL)
    frame_packs.pack(fill=BOTH, expand=1)
    latest_data = data[['date', 'open', 'close', 'low', 'high', 'pctChg']].tail(10)
    # k线信息
    k_lines_msg = Message(stock_info, text=str(latest_data), width=460)
    frame_packs.add(k_lines_msg)
    # 最大最小值
    max_panes = PanedWindow(stock_info,  sashrelief=SUNKEN)
    max_panes.add(Label(stock_info, text='30天最大值', font=('Arial', 14)))
    high_max = data['high'].max()
    max_panes.add(Label(stock_info, text=str(high_max), font=('Arial', 14)))
    min_panes = PanedWindow(stock_info,  sashrelief=SUNKEN)
    min_panes.add(Label(stock_info, text='30天最小值', font=('Arial', 14)))
    low_min = data['low'].min()
    min_panes.add(Label(stock_info, text=str(low_min), font=('Arial', 14)))
    frame_packs.add(max_panes)
    frame_packs.add(min_panes)
    sec_info = Text(stock_info)
    sec_info.tag_config('tag_1', foreground='blue', background='pink', font=('Arial', 14))
    sec_info.tag_config('tag_2',  font=('Arial', 14))
    frame_packs.add(sec_info)
    is_closed = False

    def check(sec):
        nonlocal is_closed
        while not is_closed:
            print('check')
            sec_data = gl.get_sec(stock.replace('sh', '1').replace('sz', '0'))['data']['details']
            latest_num = sec_data[len(sec_data) - 1]
            sec_info.insert(1.0, '%s\r\n' % latest_num, 'tag_2')
            latest_info = sec_data[len(sec_data) - 1]
            latest_price = latest_info.split(',')[1]
            if float(high_max) * buy_tips > float(latest_price):
                sec_info.insert(2.0, '请买入！！！\r\n', 'tag_1')
            elif float(low_min) * sell_tips < float(latest_price):
                sec_info.insert(2.0, '请卖出！！！\r\n', 'tag_1')
            time.sleep(sec)
    t = threading.Thread(target=check, args=(3,))
    t.setDaemon(True)
    t.start()

    def close_timer():
        nonlocal is_closed
        is_closed = True
        stock_info.destroy()
    stock_info.protocol('WM_DELETE_WINDOW', close_timer)
    # 会阻塞ui线程，所以应该还是要重启线程处理才行
    # 应该单独弄个线程或者进程，然后进行事件通知



class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()
        gl.login()

    def createWidgets(self):
        self.master.geometry('400x200')
        Label(self.master, text='股票代码', font=('Arial', 14)).place(x=10, y=20)
        Label(self.master, text='买入提示', font=('Arial', 14)).place(x=10, y=60)
        Label(self.master, text='卖出提示', font=('Arial', 14)).place(x=10, y=100)
        var_usr_name = StringVar()
        var_usr_name.set('sh.000001')
        self.entry_stock = Entry(self.master, textvariable=var_usr_name, font=('Arial', 14))
        self.entry_stock.place(x=120, y=20)
        buy_tips = StringVar()
        buy_tips.set('0.6')
        self.entry_buy = Entry(self.master, textvariable=buy_tips, font=('Arial', 14))
        self.entry_buy.place(x=120, y=60)
        sell_tips = StringVar()
        sell_tips.set('1.4')
        self.entry_sell = Entry(self.master, textvariable=sell_tips, font=('Arial', 14))
        self.entry_sell.place(x=120, y=100)
        self.check_btn = Button(self.master, text='查看', command=self.check, font=('Arial', 14))
        self.check_btn.place(x=150, y=140)

    def check(self):
        buy_tips = self.entry_buy.get()
        try:
            buy_tips = float(buy_tips)
        except Exception as e:
            messagebox.showinfo('提示', '买入请输入小数')
            return
        sell_tips = self.entry_sell.get()
        try:
            sell_tips = float(sell_tips)
        except Exception as e:
            messagebox.showinfo('提示', '卖出请输入小数')
            return
        stock = self.entry_stock.get()
        check(self, buy_tips, sell_tips, stock)


if __name__ == '__main__':
    app = Application()
    # 设置窗口标题:
    app.master.title('股票行情')
    # 主消息循环:
    app.mainloop()
